package ar.edu.itba.it.paw.services.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ar.edu.itba.it.paw.dao.UserDAO;
import ar.edu.itba.it.paw.domain.User;
import ar.edu.itba.it.paw.domain.exceptions.RegisteredMailException;
import ar.edu.itba.it.paw.domain.exceptions.RegisteredUsernameException;
import ar.edu.itba.it.paw.services.UserServices;

@Service
public class UserServicesImpl implements UserServices{

	private UserDAO dao;
	
	@Autowired
	public UserServicesImpl (UserDAO dao){
		this.dao = dao;
	}

	
	public void addUser(User user) throws RegisteredUsernameException, RegisteredMailException{
		/*El usuario ya viene validado por la clase*/
		/*Validar que no exista otro mail igual y otro usuario igual*/
		if(!dao.existsUser(user)){
			dao.addUser(user);
		}
		else{
			if(dao.existsMail(user)){
				throw new RegisteredMailException();
			}
			if(dao.getUser(user.getUsername()) != null){
				throw new RegisteredUsernameException(); 
			}
		}
	}
	
	/*Si no hay usuario devuelve null*/
	public User getUser(String username){
		if(!username.equals(""))
			return dao.getUser(username);
		else	
			return null;
	}
	
	/*Si no hay usuario devuelve null*/
	public User getUser(int user_id){
		if(user_id > 0)
			return dao.getUser(user_id);
		else
			return null;
	}
	
	
	public boolean authenticate(String username, String password){
		User user;
		
		if((user = dao.getUser(username)) != null){
			if(user.getPassword().equals(password)){
				return true;
			}
		}
		
		return false;
	}


	@Override
	public void updateUser(User user) {
		dao.updateUser(user);
	}

}
